/** 
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
* 
* MeetTaskDetailService
* 任务信息详情表
* 
* 修改纪录
* 2020-08-31 版本：1.0 shenyouyi 创建。
* @version 版本：1.0
* @author 作者：shenyouyi
* 创建日期：2020-08-31
*/
package com.topscomm.meet.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.topscomm.base.service.IBaseCboUserExtendService;
import com.topscomm.base.service.IBaseTeamUserService;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboOrgService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.meet.MeetSystemConst;
import com.topscomm.meet.pojo.MeetTaskDetailEntity;
import com.topscomm.meet.pojo.MeetTaskMasterEntity;
import com.topscomm.meet.service.IMeetTaskDetailService;
import com.topscomm.meet.service.IMeetTaskMasterService;
import com.topscomm.meet.service.ISmsWorkTasksCloseService;
import com.topscomm.meet.service.impl.auto.MeetTaskDetailServiceAuto;
import com.topscomm.meet.vo.OAResult;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;

@Service(value = "meetTaskDetailService")
@Scope(value = "singleton")
public class MeetTaskDetailService extends MeetTaskDetailServiceAuto implements IMeetTaskDetailService {

	@Autowired
	private IBaseCboUserExtendService baseCboUserExtendService;
	@Autowired
	private IBaseTeamUserService baseTeamUserService;
	@Autowired
	private IMeetTaskMasterService meetTaskMasterService;
	@Autowired
	private ICboUserService cboUserService;
	@Autowired
	private ICboDeptService cboDeptService;
	@Autowired
	private ICboOrgService cboOrgService;
	@Autowired
	private ISmsWorkTasksCloseService smsWorkTasksCloseService;

	/**
	 * @author: shenyouyi
	 * @date: 2020-08-31
	 * @param: master
	 * @return
	 * @description: 根据任务maser创建任务detail
	 * @modify:
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void createTaskDetailFromMaster(MeetTaskMasterEntity master) {
		List<Map<String, Object>> userMapList = this.searchUsersByCondition(master);
		List<BasicEntity> meetTaskDetailEntityList = this.initMeetTaskDetailList(master, userMapList);
		this.insertBatch(meetTaskDetailEntityList);
		meetTaskMasterService.deleteById(String.valueOf(master.getId()));
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020-08-31
	 * @param: meetTaskDetailEntityList
	 * @return
	 * @description: 批量创建OA任务
	 * @modify:
	 */
	@Override
	public void createOATask(List<MeetTaskDetailEntity> meetTaskDetailEntityList) {
		for (MeetTaskDetailEntity meetTaskDetailEntity : meetTaskDetailEntityList) {
			Map<String, Object> paraOA = meetTaskDetailEntity.convertToMap();
			paraOA.put("sourcesys", MeetSystemConst.OATaskSourceInfo.Sourcesys);
			paraOA.put("sourcemodule", MeetSystemConst.OATaskSourceInfo.Sourcemodule);
			paraOA.put("sourceid", meetTaskDetailEntity.getMeetid());
			// 设置消息是否提醒
			paraOA.put("messagesend", "1");
			String paraOAStr = JSON.toJSONString(paraOA);
			String oaResultJson = smsWorkTasksCloseService.submitFromMeet(paraOAStr);
			OAResult<String> oaResult = JSON.parseObject(oaResultJson, OAResult.class);
			if (oaResult.getSuccess()) {// 如果创建成功，则删除任务记录
				this.deleteById(String.valueOf(meetTaskDetailEntity.getId()));
			} else { // 如果失败，则将错误次数+1
				int failedtimes = meetTaskDetailEntity.getFailedtimes() + 1;
				meetTaskDetailEntity.setFailedtimes(failedtimes);
				this.updateEntity(meetTaskDetailEntity);
			}
		}
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020-08-31
	 * @param: master
	 * @param: userMapList
	 * @return
	 * @description: 实例化任务明细表
	 * @modify:
	 */
	private List<BasicEntity> initMeetTaskDetailList(MeetTaskMasterEntity master,
			List<Map<String, Object>> userMapList) {
		List<BasicEntity> resultList = new ArrayList<>();
		StringBufferProxy sql = new StringBufferProxy();
		for (Map<String, Object> userMap : userMapList) {
			MeetTaskDetailEntity meetTaskDetailEntity = new MeetTaskDetailEntity();
			BeanUtils.copyProperties(master, meetTaskDetailEntity);
			meetTaskDetailEntity.setId(0L);
			meetTaskDetailEntity.setFailedtimes(0);
			// 设置办理人信息
			String handleusercode = ConvertUtil.convertToString(userMap.get("code"));
			meetTaskDetailEntity.setHandleusercode(handleusercode);
			meetTaskDetailEntity.setHandleusername(ConvertUtil.convertToString(userMap.get("name")));
			// 设置归属部门信息--办理人所在部门
			sql.clear();
			sql.appendSingle(CboUserEntity.FieldCode + " = '{0}'", handleusercode);
			CboUserEntity cboUserEntity = cboUserService.queryObjectByWhere(sql.toString());
			CboDeptEntity cboDeptEntity = cboDeptService.queryById(String.valueOf(cboUserEntity.getDeptid()));
			meetTaskDetailEntity.setRelegationdeptcode(cboDeptEntity.getCode());
			meetTaskDetailEntity.setRelegationdeptname(cboDeptEntity.getName());
			// 设置归属公司信息
			CboOrgEntity cboOrgEntity = cboOrgService.queryById(String.valueOf(cboUserEntity.getOrgid()));
			meetTaskDetailEntity.setRelegationorgcode(cboOrgEntity.getCode());
			meetTaskDetailEntity.setRelegationorgname(cboOrgEntity.getName());
			resultList.add(meetTaskDetailEntity);
		}
		return resultList;
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020-08-31
	 * @param: master
	 * @return
	 * @description:
	 * @modify:
	 */
	private List<Map<String, Object>> searchUsersByCondition(MeetTaskMasterEntity master) {
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		String roleids = master.getHandleroleids();
		if (!StringUtil.isEmpty(roleids)) {
			resultList.addAll(baseCboUserExtendService.searchUserByRoleIds(roleids));
		}
		String deptcodes = master.getHandledeptcodes();
		if (!StringUtil.isEmpty(deptcodes)) {
			resultList.addAll(baseCboUserExtendService.searchUsersByDeptCodes(deptcodes));
		}
		String teamids = master.getHandleteamids();
		if (!StringUtil.isEmpty(teamids)) {
			resultList.addAll(baseTeamUserService.searchUsersByTeams(teamids));
		}
		String handleusercodes = master.getHandleusercodes();
		String handleusernames = master.getHandleusernames();
		if (!StringUtil.isEmpty(handleusercodes)) {
			resultList.addAll(this.searchUsersByCodes(handleusercodes, handleusernames));
		}
		// 去除重复数据
		resultList = resultList.stream().distinct().collect(Collectors.toList());
		return resultList;
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-26
	 * @param: usercodes
	 * @description: 根据用户编码获取用户信息
	 * @modify:
	 */
	private List<Map<String, Object>> searchUsersByCodes(String usercodes, String usernames) {
		String[] usercodeArray = usercodes.split(",");
		String[] usernameArray = usernames.split(",");
		List<Map<String, Object>> userMapList = new ArrayList<>();
		for (int i = 0; i < usercodeArray.length; i++) {
			Map<String, Object> userMap = new HashMap<>();
			userMap.put("code", usercodeArray[i]);
			userMap.put("name", usernameArray[i]);
			userMapList.add(userMap);
		}
		return userMapList;
	}

	/**
	 * @description: 从OA系统取得编码值
	 * @return
	 * @author: wanghongwei
	 * @date: 2020年9月9日下午2:31:18
	 * @modify:
	 */
	@Override
	public Map<String, Object> searchCodeMapFromOA() {
		String oaResultJson = smsWorkTasksCloseService.createItemListFromMeet();
		OAResult<String> oaResult = JSON.parseObject(oaResultJson, OAResult.class);
		if (!oaResult.getSuccess()) {
			throw new BusinessException("查询OA系统任务列表失败，请稍后重试。");
		}
		String jsonData = oaResult.getData();
		Map<String, Object> codeMap = JSON.parseObject(jsonData, Map.class);
		return codeMap;
	}
}
